package com.dayaokeji.rhythmschoolstudent.client.home.course

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.dayaokeji.rhythmschoolstudent.R
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager
import com.dayaokeji.rhythmschoolstudent.client.common.base.ActivityTemplateMethod
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.QuestionAndAnswerFragment
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.AnswerCallback
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils
import com.dayaokeji.server_api.ApiUtils
import com.dayaokeji.server_api.ServerResponse
import com.dayaokeji.server_api.api.ExamApi
import com.dayaokeji.server_api.domain.CommitExam
import com.dayaokeji.server_api.domain.ExamQuestion
import com.dayaokeji.server_api.domain.SubjectAnswer
import com.dayaokeji.server_api.domain.UpdateExam
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_student_qa.*
import org.greenrobot.eventbus.EventBus
import retrofit2.Call

class StudentQAActivity : BaseActivity() , ActivityTemplateMethod , AnswerCallback {
    companion object {

        private const val EXAM_ID = "exam_id";
        private const val EXAM_TITLE = "exam_title"
        private const val IS_APPROVED = "is_approved"

        fun navigation(context: Context,examId: Int,examTitle: String,isApproved: Boolean) {
            val intent = Intent(context, StudentQAActivity::class.java)
            intent.putExtra(EXAM_ID,examId)
            intent.putExtra(EXAM_TITLE,examTitle)
            intent.putExtra(IS_APPROVED,isApproved)
            context.startActivity(intent)
        }
    }

    private val examApi: ExamApi by lazy { ApiUtils.getApi(ExamApi::class.java) }
    private var examQuestionCall: Call<ServerResponse<List<ExamQuestion>>>? = null
    private var commitExamCall:Call<ServerResponse<Void>>? = null
    private var examId: Int = -1
    private var examTitle: String? = null
    private var subjectAnswer: SubjectAnswer? = null
    private var isApproved: Boolean = false
    private var isSaveInstanceState: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_student_qa)
        toolbar?.let {
            setSupportActionBar(it)
        }

        init()
    }

    override fun init() {
        examId = intent.getIntExtra(EXAM_ID,-1)
        examTitle = intent.getStringExtra(EXAM_TITLE)
        isApproved = intent.getBooleanExtra(IS_APPROVED,false)
        if (examId == -1 || TextUtils.isEmpty(examTitle)) {
            ToastUtils.info(R.string.data_incorrect)
            return
        }
        super.init()
    }

    override fun setupView() {
        if (isApproved) {
            btnSubmitSubject.visibility = View.GONE
        }
    }

    override fun setupViewData() {
        reqSubjectInfo()
    }

    private fun reqSubjectInfo() {
        UserUtils.getUserInfo()?.let {
            val id = it.id
            examQuestionCall = examApi.queryExamQuestion(examId, id)
            examQuestionCall?.enqueue(object : ServerCallback<List<ExamQuestion>>() {
                override fun onResponse(success: Boolean, response: ServerResponse<List<ExamQuestion>>?) {
                    if (success) {
                        response?.let {
                            val body = it.body
                            body?.let {
                                if (it.isNotEmpty()) {
                                    val examQuestion = it[0]
                                    examQuestion.content = examTitle
                                    setQAFragment(examQuestion)
                                }
                            }
                        }
                    }
                }
            })
        }
    }

    private fun setQAFragment(examQuestion: ExamQuestion) {
        if (!isSaveInstanceState) {
            val subjectFragment = QuestionAndAnswerFragment.newInstance(examQuestion).setShowExamResult(isApproved)
            supportFragmentManager.beginTransaction().replace(R.id.fl_content,subjectFragment).commitAllowingStateLoss()
        }
    }

    override fun callback(subjectAnswer: SubjectAnswer?) {
        this.subjectAnswer = subjectAnswer
    }

    /**
     * 提交按钮事件
     */
    fun submitSubjectClick(view: View) {
        if (subjectAnswer != null) {
            if (TextUtils.isEmpty(subjectAnswer?.answer) && subjectAnswer?.resourceList!!.isEmpty()) {
                ToastUtils.info("请填写答案之后提交")
            }else{
                val answerList: ArrayList<SubjectAnswer> = arrayListOf()
                subjectAnswer?.let {
                    answerList.add(it)
                    examSubmit(answerList)
                }
            }
        }else{
            ToastUtils.info("请填写答案之后提交")
        }
    }

    private fun examSubmit(answerList: ArrayList<SubjectAnswer>) {
        val commitExam = CommitExam()
        commitExam.id = examId
        commitExam.examAnswerList = answerList
        Logger.d(commitExam.toString())
        commitExamCall = examApi.commitExam(commitExam)
        commitExamCall?.enqueue(object : ServerCallback<Void>(this, "正在提交中...") {
            override fun onResponse(success: Boolean, response: ServerResponse<Void>) {
                if (success) {
                    ToastUtils.success("提交成功")
                    EventBus.getDefault().post(UpdateExam())
                    ActivityStackManager.finish()
                }
            }
        })
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        isSaveInstanceState = true
    }
}
